#include "imageManager.h"
#include <easyx.h>
#include <iostream>

imageManager* imageManager::getInstaance()
{
	static imageManager im;
	return &im;
}

IMAGE* imageManager::loadImage(const std::string& file, int w, int h)
{
	auto img = new IMAGE;

	::loadimage(img, file.data(), w, h);

	if (img->getwidth() == 0 || img->getheight() == 0) {
		std::cout << "load image<" << file << ">failed" << std::endl;
		delete img;
		return nullptr;
	}
	return img;
}

void imageManager::cacheImage(const std::string& tag, const std::string& file, int w, int h)
{	
	IMAGE* img = loadImage(file, w, h);
	if (img) {
		m_inages.emplace(tag, img);
	}
}
IMAGE* imageManager::getImage(const std::string& tag)
{
	auto it = m_inages.find(tag);

	if (it == m_inages.end()) {
		std::cout << "文件错误<" << tag << ">failed" << std::endl;
		return nullptr;
	}
	return it->second.get();

}



void imageManager::drawImg(int x, int y, IMAGE* src)
{

	if (src->getwidth()== 0 || src->getheight() == 0) {
		std::cout << "读取错误" << std::endl;

		return ;
	}
	DWORD* pwin = GetImageBuffer();
	DWORD* psrc = GetImageBuffer(src);
	int win_w = getwidth();
	int win_h = getheight();
	int src_w = src->getwidth();
	int src_h = src->getheight();


	int real_w = (x + src_w > win_w) ? win_w - x : src_w;
	int real_h = (y + src_h > win_h) ? win_h - y : src_h;
	if (x < 0) { psrc += -x;         real_w -= -x;   x = 0; }
	if (y < 0) { psrc += (src_w * -y);   real_h -= -y;   y = 0; }

	pwin += (win_w * y + x);


	for (int iy = 0; iy < real_h; iy++)
	{
		for (int ix = 0; ix < real_w; ix++)
		{
			byte a = (byte)(psrc[ix] >> 24);
			if (a > 100)
			{
				pwin[ix] = psrc[ix];
			}
		}
		pwin += win_w;
		psrc += src_w;
	}
}

void imageManager::drawImg(int x, int y, int dstW, int dstH, IMAGE* src, int srcX, int srcY)
{

	DWORD* pwin = GetImageBuffer();
	DWORD* psrc = GetImageBuffer(src);
	int win_w = getwidth();
	int win_h = getheight();
	int src_w = src->getwidth();
	int src_h = src->getheight();



	int real_w = (x + dstW > win_w) ? win_w - x : dstW;
	int real_h = (y + dstH > win_h) ? win_h - y : dstH;
	if (x < 0) { psrc += -x;         real_w -= -x;   x = 0; }
	if (y < 0) { psrc += (dstW * -y);    real_h -= -y;   y = 0; }


	pwin += (win_w * y + x);


	for (int iy = 0; iy < real_h; iy++)
	{
		for (int ix = 0; ix < real_w; ix++)
		{
			byte a = (byte)(psrc[ix + srcX + srcY * src_w] >> 24);
			if (a > 100)
			{
				pwin[ix] = psrc[ix + srcX + srcY * src_w];
			}
		}

		pwin += win_w;
		psrc += src_w;
	}
}
